// challeng/pages/xplay/xplay.js
var app = getApp();
var answerTimer = null;
Page({
	onShareAppMessage:function(){
	  var that = this;
	  var mid = that.data.mem.id;
	  var sharedata = that.data.shareData;
	  sharedata.path = 'challeng/pages/index/index?mid='+mid+'&gType=5';
	  return {
		  title: sharedata.title,
	     // desc: sharedata.desc,
	      path: sharedata.path,
	      imageUrl:sharedata.pic,
	      success(res){
	    	  var shareTicket = res.shareTickets[0] // 获取 shareTicket
	    	  wx.getShareInfo({
	              shareTicket: shareTicket,
	              complete(res) {
	            	  app.util.request({
		    	        url: 'entry/wxapp/addnums',
		    	        data: {
		    	            m : 'junsion_challeng',
		    	            t : 1,
		    	            mid : that.data.openid,
		    	            iv : res.iv,
		    	            encryptedData : res.encryptedData,
		    	        },
		    	        success: function (res) {
		    	        	if (res.data.code == 1) {
		                        that.setData({ challeng_num: parseInt(res.data.num)});
	                        	wx.showToast({
	                        		title:'次数\t+'+res.data.num,
	                        		icon:'none',
	                				mask:true,
	                				duration:1000
	                			});
		    	    	    } 
		    	        	else{
		    	        		 wx.showModal({title:res.data.msg,showCancel:false});
		    	        	}
		    	        }
		    	    }); 
	                
	              }
	          });
	      },
	      fail: function(res) {
	        // 转发失败
	    	  console.log(res);
	      }
	  }
  },
  data: {
	game_bg:'',
	gametoken:'',
	str_time:'',
	openid:'',
  	mem:{},
  	total:0,
  	cur_num:0,
  	cur_i:0,
  	times:[],
  	g_nums:[],
	resettime:5,
	answerIng:false,
	problem:[],
	userSel:[],
  	
  	beginCountDown: 5,//游戏开始--倒计时
    gamingStatus: 'notBegin',//游戏状态4个。notBegin未开始，running正在运行，fail挑战失败,success挑战成功
  },
  onLoad: function (options) {
	  var that = this;
	  wx.showLoading({title:'数据加载中...'});
	  app.sysInit(this,function(res){
		  app.getUserInfo(function (res) {
			  var openid = res['openid'];
			  //获取分享内容
			  app.getShareData(function(res){
				  that.setData({shareData:res.data});
			  },openid,5);
			  
			  that.setData({openid:openid});
			  app.util.request({
				  url: 'entry/wxapp/xplay',
				  data: {
					  m: 'junsion_challeng',
					  t: 1,
					  openid:openid,
					  game:5,
				  },
				  success: function (res) {
					  wx.hideLoading();
					  if(res.data.code==0 || res.data.code==2){
						  var code = res.data.code;
						  wx.showModal({
							  title:res.data.msg,
							  showCancel:false,
							  success: function(res) {
								  wx.showLoading({title:'数据加载中...'});
								  if(code==2)
									  var url = '../index/index?gobuy=1';
								  else var url = '../index/index';
								  wx.redirectTo({
									  url: url
								  })
							  }
						  });
					  }
					  else{
						  that.setData({
							  game_bg:res.data.game_bg,
							  gametoken:res.data.gametoken,
							  str_time:res.data.str_time,
							  mem:res.data.mem,
							  beginCountDown:res.data.down,
							  total:res.data.total,
							  times:res.data.times,
							  g_nums:res.data.g_nums,
							  problem:res.data.problem,
							  answer:res.data.problem[0].check_answer,
							  answerIng:false,
						  });
						  if(parseInt(res.data.times[0])>0){
							  that.setData({
								  resettime:res.data.times[0],
							  });
						  }
						  else if(parseInt(res.data.times[1])>0){
							  that.setData({
								  resettime:res.data.times[1],
							  });
						  }
						  else if(parseInt(res.data.times[2])>0){
							  that.setData({
								  resettime:res.data.times[2],
							  });
						  }
						  else{
							  that.setData({
								  resettime:5,
							  });
						  }
						  that.beginCountDown(res.data.down);//游戏主入口
					  }
				  },
			  });
		  });
	  });
	  var music = wx.getStorageSync('music');
      that.setData({
		  music:music.music,
		  err_music:music.err_music,
	  });
	  
  },
  onReady: function () {
	  var that=this;
  	  this.audioCtx = wx.createAudioContext('myAudio')
      this.errAudio = wx.createAudioContext('errAudio')
      this.audioCtx.play()
  },
  goAdd:function(e){
	  var that = this;
	  var dataset = e.currentTarget.dataset;
  	  var index = dataset.index;
  	  var userSel = that.data.answer;
  	  if(userSel[index]){
  		  userSel[index] = '';
  		  var cur_i = parseInt(that.data.cur_i);
  		  cur_i--;
  		  that.setData({answer:userSel,cur_i:cur_i});
  	  }
  },
  goCheck:function(e){
  	  var that = this;
	  var dataset = e.currentTarget.dataset;
	  var index = dataset.index;
	  var cur_num = parseInt(that.data.cur_num);
	  var answers = that.data.problem[cur_num].answers;
	  var userSel = that.data.answer;
	  var cur_i = parseInt(that.data.cur_i);
	  for(var ii=0;ii<userSel.length;ii++){
		  if(!userSel[ii] || userSel[ii]==''){
			userSel[ii] = answers[index];
			break;
		  }
	  }
	  cur_i++;
	  that.setData({answer:userSel,cur_i:cur_i});
	  if(cur_i==userSel.length){
		  if(that.data.answerIng) return false;
		  that.setData({answerIng:true});
		  clearInterval(answerTimer);//用户选择答案之后就清除定时器，防止超时失败
		//判断答案是否正确
	  		var user_anwer = '';
	  		for(var jj=0;jj<userSel.length;jj++){
	  			user_anwer+=userSel[jj];
	  		}
	  		var right_anwer = app.strencode(that.data.problem[cur_num].answer,that.data.str_time);
	  		if(right_anwer!=user_anwer){
	  			that.audioCtx.pause()
	  			app.tzfail(that,5);//挑战失败
	  		}
	  		else{
	  			cur_num++;
	  			if (cur_num == parseInt(that.data.total)) {
					app.checkReward(that,5,cur_num);//中奖了
					return false;
				}
				if(parseInt(that.data.g_nums[0])>cur_num){
					var now_times=that.data.times[0];
				}
				else if(parseInt(that.data.g_nums[1])>cur_num){
					var now_times=that.data.times[1];
				}
				else if(parseInt(that.data.g_nums[2])>cur_num){
					var now_times=that.data.times[2];
				}
				else{
					var now_times=5;
				}
				if(cur_num % 10 == 0){
	  				//获取新的题目
	  				app.util.request({
	  	  				url: 'entry/wxapp/checkxplay',
	  	  				data: {
	  	  					m: 'junsion_challeng',
	  	  					t: 1,
	  	  					mid:that.data.mem.id,
	  	  					str_time:that.data.str_time,
	  	  					game:5,
	  	  				},
	  	  				success: function (res) {
	  	  					if(res.data.code==1){
		  	  					that.setData({
		  	  						problem: that.data.problem.concat(res.data.problem),
			  	  	            });
		  	  					that.timeCountDown(now_times);
			  	  				that.setData({answer:that.data.problem[cur_num].check_answer,cur_i:0,answerIng:false,cur_num:cur_num});
	  	  					}
	  	  					else{
	  	  						wx.showModal({
	  	  							title:res.data.msg,
	  	  							showCancel:false,
	  	  							success: function(res) {
	  	  								wx.redirectTo({
	  	  									url: '../index/index'
	  	  								})
	  	  							}
	  	  						});
	  	  					}
	  	  				}
	  	  			});
	  			}
	  			else{
	  				that.timeCountDown(now_times);
  	  				that.setData({answer:that.data.problem[cur_num].check_answer,cur_i:0,answerIng:false,cur_num:cur_num});
	  			}
	  		}
	  }
  },
  onUnload: function(){
	  clearInterval(answerTimer);
  },
  timeCountDown:function(myTime){
  	var that=this;
  	if(answerTimer){
  		clearInterval(answerTimer);
  		that.setData({ resettime: myTime });
  	}
		answerTimer = setInterval(function () {
  		if(that.data.answerIng){
  			return false;
  		}
  		that.setData({ resettime: --myTime });
  		if (myTime <= 0) {
  			//时间到，失败
  			clearInterval(answerTimer);
  			//失败处理
  			that.audioCtx.pause()
  			app.tzfail(that,5);//挑战失败
  		}
  	}, 1000);
  	
  },
//游戏开始倒计时
  beginCountDown:function(countTime){
      var that=this;
      var timer = setInterval(function () {
          that.setData({ beginCountDown: --countTime });
          if (countTime <= 0) {
              clearInterval(timer);
              that.setData({
                  gamingStatus:'running'
              });
              that.timeCountDown(parseInt(that.data.resettime));//游戏主入口
          }
      }, 1000)
  }

})